class_name NPCWithUI
extends Area2D

# NPC配置
@export var npc_name: String = "村民"
@export var dialogue_data: Array[Dictionary] = []
@export var npc_portrait: Texture2D

# 节点引用
@onready var sprite: Sprite2D = $Sprite2D
@onready var collision: CollisionShape2D = $CollisionShape2D
@onready var dialogue_ui: Control = $DialogueUI

# 对话状态
var player_in_range: bool = false
var dialogue_active: bool = false
var current_dialogue: Array[Dictionary] = []
var current_line: int = 0
var auto_timer: Timer
var auto_advance_time: float = 5.0

func _ready():
	# 连接信号
	body_entered.connect(_on_body_entered)
	body_exited.connect(_on_body_exited)
	
	# 设置碰撞检测
	collision_layer = 0
	collision_mask = 1  # 检测玩家层
	
	# 创建自动播放计时器
	auto_timer = Timer.new()
	auto_timer.wait_time = auto_advance_time
	auto_timer.timeout.connect(_on_auto_advance)
	auto_timer.one_shot = true
	add_child(auto_timer)
	
	# 初始化对话UI
	if dialogue_ui:
		dialogue_ui.hide_dialogue()
	
	# 设置默认对话数据（如果没有配置）
	if dialogue_data.is_empty():
		setup_default_dialogue()

func setup_default_dialogue():
	"""设置默认对话内容"""
	dialogue_data = [
		{
			"speaker": "npc",
			"text": "你好！欢迎来到这里。"
		},
		{
			"speaker": "player",
			"text": "你好，请问这里是什么地方？"
		},
		{
			"speaker": "npc",
			"text": "这里是新手村，你可以在这里学习基本的游戏操作。"
		},
		{
			"speaker": "player",
			"text": "谢谢你的帮助！"
		},
		{
			"speaker": "npc",
			"text": "不客气，祝你游戏愉快！"
		}
	]

func _input(event):
	"""处理输入事件"""
	if dialogue_active and event.is_action_pressed("ui_accept"):
		next_line()

func _on_body_entered(body):
	"""玩家进入NPC范围"""
	if body.has_method("get_groups") and body.is_in_group("player"):
		player_in_range = true
		print("玩家接近NPC: ", npc_name)
		# 立即触发对话
		start_dialogue()

func _on_body_exited(body):
	"""玩家离开NPC范围"""
	if body.has_method("get_groups") and body.is_in_group("player"):
		player_in_range = false
		print("玩家离开NPC: ", npc_name)
		# 如果对话正在进行，结束对话
		if dialogue_active:
			end_dialogue()

func start_dialogue():
	"""开始对话"""
	if not dialogue_active and dialogue_ui:
		current_dialogue = dialogue_data
		current_line = 0
		dialogue_active = true
		
		# 显示对话UI
		dialogue_ui.show_dialogue()
		
		# 显示第一行对话
		show_current_line()
		
		# 暂停玩家移动
		var player = get_tree().get_first_node_in_group("player")
		if player and player.has_method("set_can_move"):
			player.set_can_move(false)

func next_line():
	"""显示下一行对话"""
	if not dialogue_active:
		return
	
	# 停止自动播放计时器
	auto_timer.stop()
	
	current_line += 1
	
	if current_line >= current_dialogue.size():
		# 对话结束
		end_dialogue()
	else:
		# 显示下一行
		show_current_line()

func show_current_line():
	"""显示当前行对话"""
	if current_line >= current_dialogue.size() or not dialogue_ui:
		return
	
	var line_data = current_dialogue[current_line]
	var speaker = line_data.get("speaker", "")
	var text = line_data.get("text", "")
	
	# 更新UI
	dialogue_ui.update_dialogue(speaker, text, npc_portrait, npc_name)
	
	# 启动自动播放计时器
	auto_timer.start()

func end_dialogue():
	"""结束对话"""
	if not dialogue_active:
		return
	
	dialogue_active = false
	auto_timer.stop()
	
	# 隐藏对话UI
	if dialogue_ui:
		dialogue_ui.hide_dialogue()
	
	# 恢复玩家移动
	var player = get_tree().get_first_node_in_group("player")
	if player and player.has_method("set_can_move"):
		player.set_can_move(true)

func _on_auto_advance():
	"""自动播放下一行"""
	next_line()

func set_auto_advance_time(time: float):
	"""设置自动播放时间"""
	auto_advance_time = time
	auto_timer.wait_time = time